<?php
namespace Home\Controller;
use Think\Controller;
// +----------------------------------------------------------------------
// | Fanwe 方维p2p借贷系统
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://www.fanwe.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 云淡风轻(88522820@qq.com)
// +----------------------------------------------------------------------

class IndexController extends  BaseController{
    //首页
    public function index(){
        //$root = get_baseroot();
        $root['response_code'] = 1;

        //print_r($GLOBALS['db_conf']); exit;

        $root['kf_phone'] = $GLOBALS['m_config']['kf_phone'];//客服电话
        $root['kf_email'] = $GLOBALS['m_config']['kf_email'];//客服邮箱

        //$pattern = "/<img([^>]*)\/>/i";
        //$replacement = "<img width=300 $1 />";
        //$goods['goods_desc'] = preg_replace($pattern, $replacement, get_abs_img_root($goods['goods_desc']));
        //关于我们(填文章ID)
        $root['about_info'] = intval($GLOBALS['m_config']['about_info']);

        $root['db_version'] = app_conf("DB_VERSION"); //数据库版本号
        $root['version'] = VERSION; //接口版本号int
        $root['page_size'] = 20;//默认分页大小
        $root['program_title'] = $GLOBALS['m_config']['program_title'];
        $root['site_domain'] = str_replace("/mapi", "", SITE_DOMAIN.APP_ROOT);//站点域名;
        $root['site_domain'] = str_replace("http://", "", $root['site_domain']);//站点域名;
        $root['site_domain'] = str_replace("https://", "", $root['site_domain']);//站点域名;
        //$root['newslist'] = $GLOBALS['m_config']['newslist'];

        $stats = site_statics();
        $root['stats'] = $stats;
        $root['virtual_money_1'] = strip_tags(number_format(floatval($stats['total_load'])/10000,3));//虚拟的累计成交额;
        $root['virtual_money_2'] = strip_tags(number_format(floatval($stats['total_rate'])/10000,3));//虚拟的累计创造收益;
        $root['virtual_money_3'] = strip_tags(number_format(floatval($stats['total_bzh'])/10000,3));//虚拟的本息保障金;

        $total_vs = $stats['total_load'];
        if($total_vs < $stats['total_rate'])
            $total_vs = $stats['total_rate'];
        if($total_vs < $stats['total_bzh'])
            $total_vs = $stats['total_bzh'];
        $root['virtual_money_1_pos']  = intval($stats['total_load']*100/$total_vs);
        $root['virtual_money_2_pos']  = intval($stats['total_rate']*100/$total_vs);
        $root['virtual_money_3_pos']  = intval($stats['total_bzh']*100/$total_vs);


        $index_list = $GLOBALS['cache']->get("MOBILE_INDEX_ADVS");

        if($index_list===false)
        {
            $advs = $GLOBALS['db']->getAll(" select * from ".DB_PREFIX."m_adv where status = 1 and `page`='top' order by sort desc ");
            $adv_list = array();
            foreach($advs as $k=>$v)
            {
                if ($v['img'] != ''){
                    $v['img'] = get_abs_img_root(get_spec_image($v['img'],640,240,1));
                    $adv_list[] = $v;
                }
            }

            $index_list['adv_list'] = $adv_list;

            //===========特别推荐================
            //publish_wait 0:已审核 1:等待审核;deal_status 0待等材料，1进行中，2满标，3流标，4还款中，5已还清
            $condition = " publish_wait = 0 AND deal_status in (1,2,4,5) and is_new = 1 OR(is_advance=1 AND start_time > ".TIME_UTC.") and is_hidden = 0 ";

            if((int)app_conf("SHOW_EXPRIE_DEAL") == 0){
                $condition .= " AND (if(deal_status = 1, start_time + enddate*24*3600 > ".TIME_UTC .",1=1)) ";
            }

            //require_once APP_ROOT_PATH.'system/deal_func.php';
            $limit = "0,5";
            $orderby = "deal_status ASC,sort DESC,id DESC";

            $result = get_deal_list($limit,0,$condition,$orderby);
            foreach ( $result ['list'] as $m => $v )
            {
                $cate_info_icon = get_abs_wap_url_root(get_abs_img_root($result['list'][$m]['cate_info']['icon']));
                $result ['list'][$m]['cate_info']['icon'] = $cate_info_icon;
                if($v['deal_status']>=4){
                    $result ['list'][$m]['progress_point'] = 100;
                }

            }

            $index_list['rec_deal_list'] = $result['list'];
            //var_dump($index_list['rec_deal_list']);
            //exit;
            //===========特别推荐END================

            //===========普通推荐================
            //publish_wait 0:已审核 1:等待审核;deal_status 0待等材料，1进行中，2满标，3流标，4还款中，5已还清
            $condition = " publish_wait = 0 AND deal_status in (1,2,4,5) and is_new = 0 and is_advance=0 AND start_time < ".TIME_UTC." and is_hidden = 0 ";

            if((int)app_conf("SHOW_EXPRIE_DEAL") == 0){
                $condition .= " AND (if(deal_status = 1, start_time + enddate*24*3600 > ".TIME_UTC .",1=1)) ";
            }

            require_once APP_ROOT_PATH.'system/deal_func.php';
            $limit = "0,3";
            $orderby = "deal_status ASC,sort DESC,id DESC";

            $result = get_deal_list($limit,0,$condition,$orderby);
            foreach ( $result ['list'] as $m => $v )
            {
                $cate_info_icon = get_abs_wap_url_root(get_abs_img_root($result['list'][$m]['cate_info']['icon']));
                $result ['list'][$m]['cate_info']['icon'] = $cate_info_icon;
                if($v['deal_status']>=4){
                    $result ['list'][$m]['progress_point'] = 100;
                }
            }

            $index_list['deal_list'] = $result['list'];

            //===========普通推荐END================


            $GLOBALS['cache']->set("MOBILE_INDEX_ADVS",$index_list);
        }
        $root['index_list'] = $index_list;

        $root['deal_cate_list'] = getDealCateArray();//分类

        if(strim($GLOBALS['m_config']['sina_app_key'])!=""&&strim($GLOBALS['m_config']['sina_app_secret'])!="")
        {
            $root['api_sina'] = 1;
            $root['sina_app_key'] = $GLOBALS['m_config']['sina_app_key'];
            $root['sina_app_secret'] = $GLOBALS['m_config']['sina_app_secret'];
            $root['sina_bind_url'] = $GLOBALS['m_config']['sina_bind_url'];
        }
        if(strim($GLOBALS['m_config']['tencent_app_key'])!=""&&strim($GLOBALS['m_config']['tencent_app_secret'])!="")
        {
            $root['api_tencent'] = 1;
            $root['tencent_app_key'] = $GLOBALS['m_config']['tencent_app_key'];
            $root['tencent_app_secret'] = $GLOBALS['m_config']['tencent_app_secret'];
            $root['tencent_bind_url'] = $GLOBALS['m_config']['tencent_bind_url'];
        }
        //检查其他设备是否已经登录,去除微信
        $is_wechat = \es_session::get("is_wechat");

        if ($is_wechat !== 1) {
            //$user_info = \es_session::get('user_info');
            $token = $GLOBALS['user_info']["token"];
            $u_token = \es_cookie::get('token');
            if (empty($u_token)) {
                \es_session::set('user_info', '');
                $GLOBALS['user_info'] = '';
                \es_cookie::delete("user_name");
                \es_cookie::delete("user_pwd");
            }
        }
        $root['is_login'] = $this->check_is_login() ;
        $root['act'] = CONTROLLER_NAME;
        $this->assign('data',$root);
        $this->display();
    }



    //框架头
    public function top()
    {
        $adm_session = es_session::get(md5(conf("AUTH_KEY")));
        $this->assign("adm_session",$adm_session);

        $navs = require_once APP_ROOT_PATH."system/admnav_cfg.php";
        foreach($navs as $k=>$v){

            if((int)app_conf("NAV_LICAI_OPEN")==0 && strpos(strtolower($v['key']),"licai")!==false){
                unset($navs[$k]);
            }
        }
        $this->assign("navs",$navs);
        $this->display();
    }
    //框架左侧
    public function left()
    {
        $navs = require_once APP_ROOT_PATH."system/admnav_cfg.php";
        $adm_session = es_session::get(md5(conf("AUTH_KEY")));
        $adm_id = intval($adm_session['adm_id']);

        $nav_key = strim($_REQUEST['key']);
        $nav_group = $navs[$nav_key]['groups'];

        foreach($nav_group as $k=>$v){
            if((int)app_conf("NAV_LICAI_OPEN")==0 && strpos(strtolower($v['key']),"licai")!==false){
                unset($nav_group[$k]);
            }
        }
        $this->assign("menus",$nav_group);
        $this->display();
    }
    //默认框架主区域
    public function main()
    {
        $adm_session = es_session::get(md5(conf("AUTH_KEY")));
        $this->assign("adm_session",$adm_session);
        $adm_id = intval($adm_session['adm_id']);
        $login_time = $GLOBALS['db']->getOne("SELECT login_time FROM ".DB_PREFIX."admin where id = $adm_id ");
        $login_time = to_date($login_time);
        $this->assign("login_time",$login_time);
        $h=to_date(TIME_UTC,"H");
        if($h<12){
            $greet ="上午好";
        }elseif($h<18){
            $greet ="下午好";
        }else{
            $greet ="晚上好";
        }
        $this->assign("greet",$greet);

        $navs = require_once APP_ROOT_PATH."system/admnav_cfg.php";
        foreach($navs as $k=>$v){

            if((int)app_conf("NAV_LICAI_OPEN")==0 && strpos(strtolower($v['key']),"licai")!==false){
                unset($navs[$k]);
            }
        }
        $this->assign("navs",$navs);

        //会员数
        $total_user = M("User")->where("user_type in (0,1) ")->count();
        $total_verify_user = M("User")->where("is_effect=1 AND user_type in (0,1) ")->count();
        $this->assign("total_user",$total_user);
        $this->assign("total_verify_user",$total_verify_user);

        //今日新个人会员
        $today=to_date(TIME_UTC,"Y-m-d");
        $total_today_user = M("User")->where("user_type = 0 AND create_date = '$today'  ")->count();
        $this->assign("total_today_user",$total_today_user);

        //今日新企业会员
        $total_today_company_user = M("User")->where("user_type = 1 AND create_date = '$today'  ")->count();
        $this->assign("total_today_company_user",$total_today_company_user);

        //筹款中中的标
        $fundraising_deal_count = M("Deal")->where("is_effect=1 AND publish_wait = 0 AND is_delete = 0 AND deal_status = 1")->count();

        //债权转让中的标
        $transfer_deal_count = M("DealLoadTransfer")->where("status = 1 ")->count();
        //今日债权转让
        $today_transfer_amount = M("DealLoadTransfer")->where("create_date = '$today' ")->sum("load_money");

        //待审核留言标
        $msgboard_count = M("DealMsgboard")->where("status = 0 ")->count();


        //满标的借款
        $suc_deal_count = M("Deal")->where("is_effect=1 AND publish_wait = 0 AND is_delete = 0 AND deal_status = 2")->count();
        //待审核的借款
        $wait_deal_count = M("Deal")->where("publish_wait in (1,3) AND is_delete = 0 ")->count();

        $wait_deal_review_count = M("Deal")->where("publish_wait = 2 AND is_delete = 0 ")->count();

        //网站垫付
        $website_pay_count =  M("GenerationRepay")->count();

        //留言待回复
        $noreply_message_count = M("Message")->where("update_time = 0")->count();

        //今日投资金额
        $today_invest_amount = M("DealLoad")->where("create_date = '$today'")->sum("money");

        //今日借款金额
        $today_borrow_amount = M("Deal")->where("start_date = '$today'")->sum("borrow_amount");

        //等待材料的借款
        $info_deal_count = M("Deal")->where("is_effect=1 AND publish_wait = 0 AND is_delete = 0 AND deal_status=0")->count();
        //等待审核的申请额度
        $quota_count = M("QuotaSubmit")->where("status=0")->count();

        //等待审核的授信额度
        $deal_quota_count = M("DealQuotaSubmit")->where("status=0")->count();

        //提现申请
        $carry_count = D("UserCarry")->where("status = 0")->count();
        //提现待付款
        $waitpay_carry_count = D("UserCarry")->where("status = 3")->count();

        //三日要还款的借款
        $threeday_repay_count = M("DealRepay")->where("((repay_time - ".TIME_UTC." +  24*3600 -1)/24/3600 between 0 AND 3) and has_repay=0 ")->count();

        //逾期未还款的
        $yq_repay_count = M("DealRepay")->where(" (".TIME_UTC." - repay_time  -  24*3600 +1 )/24/3600 > 0 and has_repay=0 ")->count();

        //未处理举报
        $reportguy_count = M("Reportguy")->where("status = 0")->count();

        //注册待审核
        $register_count = M("User")->where("login_time = 0 and login_ip='' and is_effect=0 and is_delete=0 and user_type=0 and is_black=0")->count();
        $company_register_count = M("User")->where("login_time = 0 and login_ip='' and is_effect=0 and is_delete=0 and user_type=1 and is_black=0")->count();

        //线下充值单
        $payment_id = M("Payment")->where("class_name = 'Otherpay'")->getField("id");
        $condition['payment_id'] = $payment_id;
        $offline_pay_count = floatval($GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."payment_notice where is_paid = 1 and payment_id in (SELECT id from ".DB_PREFIX."payment where class_name='Otherpay') "));
        $this->assign("offline_pay_count",$offline_pay_count);

        if(app_conf("NAV_LICAI_OPEN") == 1)
        {

            $licai_verify_count = M("Licai")->where('verify in (0,2)')->count();
            $licai_count = M("Licai")->where('verify = 1')->count();
            $licai_order_count = M("LicaiOrder")->count();
            $licai_advance_count = M("LicaiAdvance")->count();
            $licai_redempte_count = M("LicaiRedempte")->where("type = 1 and status in (0,1,2)")->count();
            $licai_wait_redempte_count = M("LicaiRedempte")->where("type = 0 and status in (0,1,2)")->count();
            $licai_near_count = $GLOBALS["db"]->getOne("select count(*) from ".DB_PREFIX."licai_order lco
		 left join ".DB_PREFIX."licai lc on lco.licai_id = lc.id where lco.status in (1,2) and lco.end_interest_date >='".to_date(TIME_UTC-15*24*3600,"Y-m-d")."' and lco.end_interest_date <='".to_date(TIME_UTC,"Y-m-d")."'");
            $licai_send_count = $GLOBALS["db"]->getOne("select count(*) from ".DB_PREFIX."licai_order lco
		 left join ".DB_PREFIX."licai lc on lco.licai_id = lc.id where lco.status =3");

            $this->assign("licai_verify_count",$licai_verify_count);
            $this->assign("licai_count",$licai_count);
            $this->assign("licai_order_count",$licai_order_count);
            $this->assign("licai_advance_count",$licai_advance_count);
            $this->assign("licai_redempte_count",$licai_redempte_count);
            $this->assign("licai_wait_redempte_count",$licai_wait_redempte_count);
            $this->assign("licai_near_count",$licai_near_count);
            $this->assign("licai_send_count",$licai_send_count);
        }

        //未处理续约申请
        $generation_repay_submit = M("GenerationRepaySubmit")->where("status = 0")->count();

        $this->assign("register_count",$register_count);
        $this->assign("company_register_count",$company_register_count);
        $this->assign("suc_deal_count",$suc_deal_count);
        $this->assign("wait_deal_count",$wait_deal_count);
        $this->assign("wait_deal_review_count",$wait_deal_review_count);
        $this->assign("info_deal_count",$info_deal_count);
        $this->assign("deal_quota_count",$deal_quota_count);
        $this->assign("quota_count",$quota_count);
        $this->assign("carry_count",$carry_count);
        $this->assign("threeday_repay_count",$threeday_repay_count);
        $this->assign("yq_repay_count",$yq_repay_count);
        $this->assign("reportguy_count",$reportguy_count);
        $this->assign("generation_repay_submit",$generation_repay_submit);
        $this->assign("waitpay_carry_count",$waitpay_carry_count);
        $this->assign("website_pay_count",$website_pay_count);
        $this->assign("noreply_message_count",$noreply_message_count);
        $this->assign("fundraising_deal_count",$fundraising_deal_count);
        $this->assign("today_invest_amount",$today_invest_amount);
        $this->assign("today_borrow_amount",$today_borrow_amount);
        $this->assign("transfer_deal_count",$transfer_deal_count);
        $this->assign("today_transfer_amount",$today_transfer_amount);
        $this->assign("msgboard_count",$msgboard_count);


        $topic_count = M("Topic")->where("is_effect = 1 and fav_id = 0")->count();
        $msg_count = M("Message")->where("is_buy = 0")->count();
        $buy_msg_count = M("Message")->count();



        $this->assign("topic_count",$topic_count);
        $this->assign("msg_count",$msg_count);
        $this->assign("buy_msg_count",$buy_msg_count);


        //充值单数
        $incharge_order_buy_count = M("PaymentNotice")->where("is_paid=1")->count();
        $this->assign("incharge_order_buy_count",$incharge_order_buy_count);


        $reminder = M("RemindCount")->find();
        $reminder['topic_count'] = intval(M("Topic")->where("is_effect = 1 and relay_id = 0 and fav_id = 0 and create_time >".$reminder['topic_count_time'])->count());
        $reminder['msg_count'] = intval(M("Message")->where("create_time >".$reminder['msg_count_time'])->count());
        /*$reminder['buy_msg_count'] = intval(M("Message")->where("create_time >".$reminder['buy_msg_count_time'])->count());
        $reminder['order_count'] = intval(M("DealOrder")->where("is_delete = 0 and type = 0 and pay_status = 2 and create_time >".$reminder['order_count_time'])->count());
        $reminder['refund_count'] = intval(M("DealOrder")->where("is_delete = 0 and refund_status = 1 and create_time >".$reminder['refund_count_time'])->count());
        $reminder['retake_count'] = intval(M("DealOrder")->where("is_delete = 0 and retake_status = 1 and create_time >".$reminder['retake_count_time'])->count());*/
        $reminder['incharge_count'] = intval(M("PaymentNotice")->where("is_paid = 1 and pay_date='".to_date(TIME_UTC,"Y-m-d")."' ")->count());

        M("RemindCount")->save($reminder);
        $this->assign("reminder",$reminder);

        //待审核认证资料
        $auth_count = $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."user_credit_file where status = 0 ");
        $this->assign("auth_count",$auth_count);

        //待补还项目
        $after_repay_count = $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal as d where publish_wait=0 and is_delete =0 AND deal_status in(4,5) AND (repay_money > round((SELECT sum(repay_money) FROM ".DB_PREFIX."deal_load_repay WHERE has_repay=1 and deal_id = d.id),2) + 1 or (repay_money >0  and (SELECT count(*) FROM ".DB_PREFIX."deal_load_repay WHERE has_repay =1 and deal_id = d.id) = 0))");
        $this->assign("after_repay_count",$after_repay_count);
        $this->display();
    }

    public function map(){
        $navs = require_once APP_ROOT_PATH."system/admnav_cfg.php";
        foreach($navs as $k=>$v){

            if((int)app_conf("NAV_LICAI_OPEN")==0 && strpos(strtolower($v['key']),"licai")!==false){
                unset($navs[$k]);
            }
        }
        $this->assign("navs",$navs);
        $this->display();
    }

    //底部
    public function footer()
    {
        $this->display();
    }

    //修改管理员密码
    public function change_password()
    {
        $adm_session = es_session::get(md5(conf("AUTH_KEY")));
        $this->assign("adm_data",$adm_session);
        $this->display();
    }
    public function do_change_password()
    {
        $adm_id = intval($_REQUEST['adm_id']);
        if(!check_empty($_REQUEST['adm_password']))
        {
            $this->error(L("ADM_PASSWORD_EMPTY_TIP"));
        }
        if(!check_empty($_REQUEST['adm_new_password']))
        {
            $this->error(L("ADM_NEW_PASSWORD_EMPTY_TIP"));
        }
        if($_REQUEST['adm_confirm_password']!=$_REQUEST['adm_new_password'])
        {
            $this->error(L("ADM_NEW_PASSWORD_NOT_MATCH_TIP"));
        }
        if(M("Admin")->where("id=".$adm_id)->getField("adm_password")!=md5($_REQUEST['adm_password']))
        {
            $this->error(L("ADM_PASSWORD_ERROR"));
        }
        M("Admin")->where("id=".$adm_id)->setField("adm_password",md5($_REQUEST['adm_new_password']));
        save_log(M("Admin")->where("id=".$adm_id)->getField("adm_name").L("CHANGE_SUCCESS"),1);
        $this->success(L("CHANGE_SUCCESS"));


    }

    public function reset_sending()
    {
        $field = trim($_REQUEST['field']);
        if($field=='DEAL_MSG_LOCK'||$field=='PROMOTE_MSG_LOCK'||$field=='APNS_MSG_LOCK')
        {
            M("Conf")->where("name='".$field."'")->setField("value",'0');
            $this->success(L("RESET_SUCCESS"),1);
        }
        else
        {
            $this->error(L("INVALID_OPERATION"),1);
        }
    }


    function manage_carry(){

        $id = intval($_REQUEST['id']);
        $manage_carry_list = $GLOBALS['db']->getAll( "select * from ".DB_PREFIX."admin_carry");
        $this->assign("manage_carry_list",$manage_carry_list);
        $this->display();
    }
    public function de_manage_carry()
    {
        $id = intval($_REQUEST['id']);

        $list = M("AdminCarry")->where('id='.$id)->delete(); // 删除

        if(!$list){
            $this->error("删除失败");
        }else{
            $this->success("删除成功");
        }
    }
    public function add_manage_carry()
    {
        $adm_session = es_session::get(md5(conf("AUTH_KEY")));
        $this->assign("adm_session",$adm_session);
        $this->display();
    }
    public function insert_carry()
    {
        $admin_id = intval($_REQUEST['admin_id']);
        $admin_name = $_REQUEST['admin_name'];
        $money = floatval($_REQUEST['money']);
        $memo = $_REQUEST['memo'];

        //$creat_time = to_date($_REQUEST['creat_time']);
        $creat_time = TIME_UTC;
        $admin_carry = array();
        $admin_carry['admin_id'] = $admin_id;
        $admin_carry['admin_name'] = $admin_name;
        $admin_carry['money'] = $money;
        $admin_carry['memo'] = $memo;
        $admin_carry['create_time'] = $creat_time;

        M("AdminCarry")->add($admin_carry);

        $this->assign("jumpUrl",u(CONTROLLER_NAME."/manage_carry"));
        $this->success(L("INSERT_SUCCESS"));
    }

    //统计信息
    function statistics(){
        //总的用户
        $user_count =  M("User")->where("user_type in(0,1)")->count();
        $this->assign("user_count",$user_count);
        //有效的未删除的
        $effect_user = $GLOBALS['db']->getAll("SELECT is_effect,count(*) as total_user FROM ".DB_PREFIX."user where is_delete = 0 and user_type in(0,1) group by is_effect ORDER BY is_effect DESC");
        $this->assign("effect_user",$effect_user);
        //回收站用户
        $trash_user_count = M("User")->where("is_delete=1 and user_type in(0,1)")->count();
        $this->assign("trash_user_count",$trash_user_count);

        //认证
        $credit_types = load_auto_cache("credit_type");
        $tcredit_files = $GLOBALS['db']->getAll("SELECT `type`,count(*) as total_user FROM ".DB_PREFIX."user_credit_file where status = 1 and passed=1 group by `type` ");
        $credit_files = array();
        foreach($tcredit_files as $k=>$v){
            $credit_files[$v['type']] = $v['total_user'];
        }
        unset($tcredit_files);
        $credit_types = $credit_types['list'];
        foreach($credit_types as $k=>$v){

            if($credit_files[$v['type']] > 0){
                $credit_types[$k]['user_count'] = $credit_files[$v['type']];
            }
            else{
                unset($credit_types[$k]);
            }
        }
        unset($credit_files);
        $this->assign("credit_types",$credit_types);

        //线上充值
        $online_pay = floatval($GLOBALS['db']->getOne("SELECT sum(money) FROM ".DB_PREFIX."payment_notice where is_paid = 1 and payment_id not in (SELECT id from ".DB_PREFIX."payment where class_name='Otherpay') "));
        $this->assign("online_pay",$online_pay);
        //线下充值金额
        $below_pay = floatval($GLOBALS['db']->getOne("SELECT sum(money) FROM ".DB_PREFIX."payment_notice where is_paid = 1 and payment_id in (SELECT id from ".DB_PREFIX."payment where class_name='Otherpay') "));
        $this->assign("below_pay",$below_pay);

        //线下充值ID
        $below_pay_id = $GLOBALS['db']->getOne("SELECT id from ".DB_PREFIX."payment where class_name='Otherpay'");
        $this->assign("below_pay_id",$below_pay_id);

        //管理员充值  （user_log管理员编辑账户）
        $manage_recharge = floatval($GLOBALS['db']->getOne("SELECT sum(money) FROM ".DB_PREFIX."user_money_log where `type`='13'"));
        $this->assign("manage_recharge",$manage_recharge);

        //管理员提现
        $manage_carry = floatval($GLOBALS['db']->getOne("SELECT sum(money) FROM ".DB_PREFIX."admin_carry "));
        $this->assign("manage_carry",$manage_carry);


        //成功提现
        $carry_amount = M("UserCarry")->where("status=1")->sum("money");
        $this->assign("carry_amount",$carry_amount);

        //第三方
        $className = getCollName();

        //环迅
        if(strtolower($className) == "ips")
        {
            //第三方充值
            $secend_pay = M("IpsDoDpTrade")->where("pErrCode='MG00000F'")->sum("pTrdAmt");
            //第三方提现
            $secend_carry_amount = M("IpsDoDwTrade")->where("pErrCode='MG00000F'")->sum("pTrdAmt");
        }
        elseif(strtolower($className) == "yeepay")
        {
            //第三方充值
            $secend_pay = M("YeepayRecharge")->where("code=1")->sum("amount");
            //第三方提现
            $secend_carry_amount = M("YeepayWithdraw")->where("code=1")->sum("amount");
        }
        elseif(strtolower($className) == "baofoo")
        {
            //第三方充值
            $secend_pay = M("BaofooRecharge")->where("code='CSD000'")->sum("amount");
            //第三方提现
            $secend_carry_amount = M("baofoo_fo_charge")->where("code='CSD000'")->sum("amount");
        }

        $this->assign("secend_pay",$secend_pay);


        $this->assign("secend_carry_amount",$secend_carry_amount);

        //总计
        $total_usre_money = $online_pay + $below_pay + $manage_recharge - $carry_amount;
        $this->assign("total_usre_money",$total_usre_money);

        /**
         * 成功借出总额 total_borrow_amount
         * 冻结中的保证金 借款人 freezen_amt
         * 冻结中的保证金 担保人 grt_freezen_amt
         * 成功借款投标奖励总额 rebate_amount
         */
        $total_borrow_amount = $GLOBALS['db']->getOne("SELECT sum(borrow_amount) as total_borrow_amount FROM ".DB_PREFIX."deal where publish_wait = 0 and is_effect = 1 and is_delete = 0 and deal_status >=4 ");
        $this->assign("borrow_amount",$total_borrow_amount);

        //已还款总额
        $has_repay_amount = floatval($GLOBALS['db']->getOne("SELECT sum(self_money) FROM ".DB_PREFIX."deal_load_repay where has_repay = 1 "));
        $this->assign("has_repay_amount",$has_repay_amount);

        //未还总额
        $need_repay_amount = floatval($GLOBALS['db']->getOne("SELECT sum(self_money) FROM ".DB_PREFIX."deal_load_repay where has_repay = 0 "));
        $this->assign("need_repay_amount",$need_repay_amount);

        //冻结中的保证金 借款人
        $freezen_amt = $GLOBALS['db']->getOne("SELECT (sum(real_freezen_amt)-sum(un_real_freezen_amt) ) as freezen_amt FROM ".DB_PREFIX."deal where publish_wait = 0 and is_effect = 1 and is_delete = 0 and deal_status >=4 AND ips_bill_no<>'' ");
        $this->assign("freezen_amt",$freezen_amt);
        //冻结中的保证金 担保人
        $grt_freezen_amt = $GLOBALS['db']->getOne("SELECT (guarantor_real_freezen_amt - un_guarantor_real_freezen_amt) as grt_freezen_amt FROM ".DB_PREFIX."deal where publish_wait = 0 and is_effect = 1 and is_delete = 0 and deal_status >=4 AND ips_bill_no<>'' ");
        $this->assign("grt_freezen_amt",$grt_freezen_amt);

        //成功借款利息总额
        $load_rate_amount = floatval($GLOBALS['db']->getOne("SELECT sum(repay_money - self_money) FROM ".DB_PREFIX."deal_load_repay where has_repay = 1 "));
        $this->assign("load_rate_amount",$load_rate_amount);

        //成功借款投标奖励总额
        $rebate_amount = $GLOBALS['db']->getOne("SELECT sum(borrow_amount*CONVERT(user_bid_rebate,DECIMAL)*0.01) as rebate_amount FROM ".DB_PREFIX."deal where publish_wait = 0 and is_effect = 1 and is_delete = 0 and deal_status >=4 ");
        $this->assign("rebate_amount",$rebate_amount);

        //注册奖励冻结资金
        $register_lock_money = floatval($GLOBALS['db']->getOne("SELECT sum(lock_money) FROM ".DB_PREFIX."user_lock_money_log where `type` = 18 "));
        $this->assign("register_lock_money",$register_lock_money);

        //逾期还款总额
        $yq_repay_amount = floatval($GLOBALS['db']->getOne("SELECT sum(repay_manage_impose_money + impose_money) FROM ".DB_PREFIX."deal_load_repay where has_repay = 1 and status in(2,3)"));
        $this->assign("yq_repay_amount",$yq_repay_amount);
        //逾期未还款总额
        $yq_norepay_amount = floatval($GLOBALS['db']->getOne("SELECT sum(repay_manage_impose_money + impose_money) FROM ".DB_PREFIX."deal_load_repay where has_repay = 0 and status in(2,3)"));
        $this->assign("yq_norepay_amount",$yq_norepay_amount);

        //逾期罚息总额
        $yq_all_amount = floatval($GLOBALS['db']->getOne("SELECT sum(impose_money) FROM ".DB_PREFIX."deal_load_repay where status in(2,3)"));
        $this->assign("yq_all_amount",$yq_all_amount);

        //借款者成交服务费
        $success_service_fee = $GLOBALS['db']->getOne("SELECT sum(borrow_amount*CONVERT(services_fee,DECIMAL)*0.01)  FROM ".DB_PREFIX."deal where publish_wait = 0 and is_effect = 1 and is_delete = 0 and deal_status >=4 ");
        $this->assign("success_service_fee",$success_service_fee);

        //借款者成交管理费
        $success_manage_fee = $GLOBALS['db']->getOne("SELECT sum(true_manage_money) FROM ".DB_PREFIX."deal_repay where has_repay=1 ");
        $this->assign("success_manage_fee",$success_manage_fee);

        //投资者成交管理费
        $load_success_manage_fee = $GLOBALS['db']->getOne("SELECT sum(true_manage_money) FROM ".DB_PREFIX."deal_load_repay where has_repay=1 ");
        $this->assign("load_success_manage_fee",$load_success_manage_fee);

        //提现手续费
        $carry_manage_fee = $GLOBALS['db']->getOne("SELECT sum(fee) FROM ".DB_PREFIX."user_carry where status = 1 ");
        $this->assign("carry_manage_fee",$carry_manage_fee);

        //理财总计
        $licai["verify_count"] = M("Licai")->where('verify in (0,2)')->count();
        $licai["count"] = M("Licai")->where('verify = 1')->count();
        $licai["order_count"] = M("LicaiOrder")->count();
        $licai["advance_count"] = M("LicaiAdvance")->count();
        $licai["redempte_count"] = M("LicaiRedempte")->where("type = 1 and status in (0,1,2)")->count();
        $licai["wait_redempte_count"] = M("LicaiRedempte")->where("type = 0 and status in (0,1,2)")->count();
        $licai["near_count"] = $GLOBALS["db"]->getOne("select count(*) from ".DB_PREFIX."licai_order lco
	 left join ".DB_PREFIX."licai lc on lco.licai_id = lc.id where lco.status in (1,2) and lco.end_interest_date >='".to_date(TIME_UTC-15*24*3600,"Y-m-d")."' and lco.end_interest_date <='".to_date(TIME_UTC,"Y-m-d")."'");
        $licai["send_count"] = $GLOBALS["db"]->getOne("select count(*) from ".DB_PREFIX."licai_order lco
	 left join ".DB_PREFIX."licai lc on lco.licai_id = lc.id where lco.status =3");

        $this->assign("licai",$licai);
        $this->display();
    }
    public function save_reset_pwd()
    {
        $mobile = addslashes(htmlspecialchars(trim($GLOBALS['request']['mobile'])));
        $verify = addslashes(htmlspecialchars(trim($GLOBALS['request']['mobile_code'])));
        $user_pwd = addslashes(htmlspecialchars(trim($GLOBALS['request']['user_pwd'])));
        $user_pwd_confirm = addslashes(htmlspecialchars(trim($GLOBALS['request']['user_pwd_confirm'])));

        $root = get_baseroot();
        $root['program_title'] = "修改密码";
        if($user_pwd != $user_pwd_confirm)
        {
            $root['response_code'] = 0;
            $root['show_err'] = $GLOBALS['lang']['USER_PWD_CONFIRM_ERROR'];

        }

        if($user_pwd == null || $user_pwd =='')
        {
            $root['response_code'] = 0;
            $root['show_err'] = $GLOBALS['lang']['USER_PWD_ERROR'];

        }


        if($verify==""){
            $root['response_code'] = 0;
            $root['show_err'] = $GLOBALS['lang']['BIND_MOBILE_VERIFY_ERROR'];

        }

        if($mobile == '')
        {
            $root['response_code'] = 0;
            $root['show_err'] = $GLOBALS['lang']['MOBILE_EMPTY_TIP'];

        }

        if(!check_mobile($mobile))
        {
            $root['response_code'] = 0;
            $root['show_err'] = $GLOBALS['lang']['FILL_CORRECT_MOBILE_PHONE'];

        }

        //$sql = "select id,code from ".DB_PREFIX."user where mobile = '".$mobile."' and bind_verify = '".$verify."' and is_delete = 0";
        $sql = "select id,code from ".DB_PREFIX."user where mobile_encrypt = AES_ENCRYPT('".$mobile."','".AES_DECRYPT_KEY."') and bind_verify = '".$verify."' and is_delete = 0";

        $user_info = $GLOBALS['db']->getRow($sql);
        $user_id = intval($user_info['id']);
        $code = $user_info['code'];

        if($user_id == 0)
        {
            $root['response_code'] = 0;
            $root['show_err'] = $GLOBALS['lang']['BIND_MOBILE_VERIFY_ERROR'];

        }else{

            $new_pwd = md5($user_pwd.$code);

            $sql = "update ".DB_PREFIX."user set user_pwd='".$new_pwd."', bind_verify = '', verify_create_time = 0 where id = ".$user_id;
            $GLOBALS['db']->query($sql);

            $root['response_code'] = 1;
            $root['show_err'] = "密码更新成功!";//$GLOBALS['lang']['MOBILE_BIND_SUCCESS'];
            $root['sql'] = $sql;

        }
        $this->assign('data',$root);
        $this->display();
    }
    public function register()
    {
        //require_once APP_ROOT_PATH."system/libs/user.php";
        $root = get_baseroot();
        $user_name = strim($_REQUEST['user_name']);//用户名
        $user_pwd = strim($_REQUEST['user_pwd']);//密码
        $user_pwd_confirm = strim($_REQUEST['user_pwd_confirm']);
        $mobile = strim($_REQUEST['mobile']);
        $mobile_code = strim($_REQUEST['mobile_code']);
        $referer = strim($_REQUEST['referer']);
        $wap_referer = "";

        if(isset($_REQUEST['r'])){
            $referer_id = intval(base64_decode($_REQUEST['r']));
            if($referer_id){
                $wap_referer = get_user_info("user_name","id=".$referer_id,"ONE");
                $root['wap_referer'] = $wap_referer;
            }

        }
        $root['program_title'] = "注册";

        $user_data = array(
            'mobile'            => $mobile,
            'user_name'        => $user_name,
            'user_pwd'         => $user_pwd,
            'user_pwd_confirm'   => $user_pwd_confirm,
            'referer'			=> $referer,
        );


        if(isset($user_data['referer']) && $user_data['referer']!=""){
            //$p_user_data = $GLOBALS['db']->getRow("SELECT id,user_type FROM ".DB_PREFIX."user WHERE mobile_encrypt = AES_ENCRYPT('".$user_data['referer']."','".AES_DECRYPT_KEY."') OR user_name='".$user_data['referer']."'");
            $p_user_data = get_user_info("id,user_type","mobile_encrypt =AES_ENCRYPT('".$user_data['referer']."','".AES_DECRYPT_KEY."') OR user_name='".$user_data['referer']."'");

            if($p_user_data["user_type"] == 3)
            {
                $user_data['referer_memo'] = $p_user_data['id'];
                $user_data['pid'] = 0;
            }
            else
            {
                $user_data['pid'] = $p_user_data["id"];
                if($user_data['pid'] > 0){
                    $refer_count = $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."user WHERE pid='".$user_data['pid']."' ");
                    if($refer_count == 0){
                        $user_data['referral_rate'] = (float)trim(app_conf("INVITE_REFERRALS_MIN"));
                    }
                    elseif((float)trim(app_conf("INVITE_REFERRALS_MIN")) + $refer_count*(float)trim(app_conf("INVITE_REFERRALS_RATE")) > (float)trim(app_conf("INVITE_REFERRALS_MAX"))){
                        $user_data['referral_rate'] =(float)trim(app_conf("INVITE_REFERRALS_MAX"));
                    }
                    else{
                        $user_data['referral_rate'] =(float)trim(app_conf("INVITE_REFERRALS_MIN")) + $refer_count*(float)trim(app_conf("INVITE_REFERRALS_RATE"));
                    }


                    if(intval(app_conf("REFERRAL_IP_LIMIT")) > 0 && $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."user WHERE register_ip ='".CLIENT_IP."' AND pid='".$user_data['pid']."'") > 0){
                        $user_data['referral_rate'] = 0;
                    }
                }
                else{
                    $user_data['pid'] = 0;
                }
            }
        }

        $check_status = $this->check_user($user_data);

        if ($check_status['status'] == 1){
            //短信验证码

            if(false && ($mobile_code=="" || $mobile_code != $GLOBALS['db']->getOne("select verify_code from ".DB_PREFIX."mobile_verify_code where mobile = '".$mobile."' AND create_time + ".SMS_EXPIRESPAN." > ".TIME_UTC."  ORDER BY id DESC")))
            {
                $root['response_code'] = 0;
                $root['show_err'] = "短信验证码错误或已失效";

            }else{
                require_once APP_ROOT_PATH."system/libs/user.php";

                $user_id = $this->add_user($user_data);

                if($user_id)
                {
                    $result = do_login_user($user_name,$user_pwd);
                    if($result['status'])
                    {
                        $user_data = $result['user'];//$result['user'];
                        $root['response_code'] = 1;
                        $root['user_login_status'] = 1;//用户登陆状态：1:成功登陆;0：未成功登陆
                        $root['show_err'] = "用户注册登陆成功";
                        $root['id'] = $user_data['id'];
                        $root['user_name'] = $user_data['user_name'];
                        $root['user_pwd'] = $user_data['user_pwd'];
                        $root['user_money'] = $user_data['money'];
                        $root['user_money_format'] = format_price($user_data['money']);//用户金额

                    }else{
                        $root['response_code'] = 0;
                        $root['user_login_status'] = 0;//用户登陆状态：1:成功登陆;0：未成功登陆
                        $root['show_err'] = "会员注册失败.";

                    }
                }else
                {
                    $root['response_code'] = 0;
                    $root['user_login_status'] = 0;//用户登陆状态：1:成功登陆;0：未成功登陆
                    $root['show_err'] = "会员注册失败.";

                }
            }
            //output($root);
        }else{
            $root['response_code'] = 0;
            $root['user_login_status'] = 0;//用户登陆状态：1:成功登陆;0：未成功登陆
            $root['show_err'] = $check_status['error_msg'];

        }
        if($_REQUEST['is_ajax'] == 1){
            echo json_encode($root);exit;
        }
        $this->assign('data',$root);
        $this->display();
    }
    public function register_do()
    {
        //require_once APP_ROOT_PATH."system/libs/user.php";

        $root = get_baseroot();
        $root['status']=0;
        $user =  \es_session::get('user_info');
        $root['session_id'] = \es_session::id();
        $user_id  = intval($user['id']);
        if ($user_id >0 && $_GET['ajax'] == 1 ){

            $root['user_login_status'] = 1;


            $real_name = strim($_REQUEST['real_name']);
            $idno = strim($_REQUEST['idno']);

            if(!$real_name)
            {
                $root['response_code'] = 0;
                $root['show_err'] = "请输入真实姓名";
                ajax_return($root);
            }

            if($idno==""){
                $root['response_code'] = 0;
                $root['show_err'] = "请输入身份证号";
                ajax_return($root);
            }

            if(getIDCardInfo($idno)==0){
                $root['response_code'] = 0;
                $root['show_err'] = "身份证号码错误！";
                ajax_return($root);
            }

            //$root['show_err'] = $idno;output($root);
            //判断该实名是否存在
            //if($GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."user where idno = '.$idno.' and id<> $user_id") > 0 ){
            //echo "SELECT count(*) FROM ".DB_PREFIX."user where idno_encrypt = AES_ENCRYPT('".$idno."','".AES_DECRYPT_KEY."') and id<> $user_id"  ;exit;
            if($GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."user where idno_encrypt = AES_ENCRYPT('".$idno."','".AES_DECRYPT_KEY."') and id<> $user_id") > 0 ){
                $root['response_code'] = 0;
                $root['show_err'] = "该实名已被其他用户认证，非本人请联系客服";
                ajax_return($root);
            }

            $user_info_re = array();
            $user_info_re['real_name_encrypt'] = $real_name;
            $user_info_re['idno_encrypt'] = $idno;
            $user_info_re['byear'] = substr($idno,6,4);
            $user_info_re['bmonth'] = substr($idno,10,2);
            $user_info_re['bday'] = substr($idno,12,2);

            $rs = idCardInfo($idno);
            if ($rs['sex'] == "男")
                $user_info_re['sex'] = 1;
            elseif ($rs['sex'] == "女")
                $user_info_re['sex'] = 0;
            else {
                $user_info_re['sex'] = -1;
            }

            $rs = $GLOBALS['db']->autoExecute(DB_PREFIX."user",$user_info_re,"UPDATE","id=".$user_id);

            if(intval(app_conf("OPEN_IPS")) > 0){
                $app_url = APP_ROOT."/index.php?m=Home&c=collocation&a=CreateNewAcct&user_type=0&is_pc=1&user_id=".$user_id."&from=".$_REQUEST['from'];
                $root['app_url'] = str_replace(array("/mapi","/wap"), "", SITE_DOMAIN.$app_url);
                $root['acct_url'] = $root['app_url'];
            }

            $root['open_ips'] = intval(app_conf("OPEN_IPS"));
            $root['response_code'] = 1;
            $root['show_err'] ="验证成功";
            $root['status']=1;
            ajax_return($root);
        }else if ($user_id ==0 && $_GET['ajax'] == 1 ){
            $root['response_code'] = 0;
            $root['show_err'] ="未登录";
            $root['user_login_status'] = 0;
            ajax_return($root);
        }

        $root['program_title'] = "身份证验证";
        //output($root);
        $this->assign('data',$root);
        $this->display();
    }


    /**
     * 生成会员数据
     * @param $user_data  提交[post或get]的会员数据
     * @param $mode  处理的方式，注册或保存
     * 返回：data中返回出错的字段信息，包括field_name, 可能存在的field_show_name 以及 error 错误常量
     * 不会更新保存的字段为：score,money,verify,pid
     */
    function add_user($user_data)
    {

        //$res = array('status'=>1,'id'=>0); //用于返回的数据

        //验证结束开始插入数据
        $user_id = 0;

        $user['user_name'] = $user_data['user_name'];
        $user['create_time'] = TIME_UTC;
        $user['create_date'] = to_date(TIME_UTC,"Y-m-d");
        $user['update_time'] = TIME_UTC;
        $user['pid'] = (int)$user_data['pid'];
        $user['referer_memo'] = $user_data['referer_memo'] ? $user_data['referer_memo'] : 'no';
        $user['referral_rate'] = $user_data['referral_rate'] ? $user_data['referral_rate'] : '1';
        $user['login_ip'] = '127.0.0.1';
        //获取默认会员组, 即升级积分最小的会员组
        $user['group_id'] = $GLOBALS['db']->getOne("select id from ".DB_PREFIX."user_group order by score asc limit 1");

        $user['is_effect'] = 1;
        $user['mobile'] = $user_data['mobile'];
        $user['mobilepassed'] = 1;//是否已经绑定手机；1：是；0：否; 手机注册的，直接就绑定手机了;
        $user['code'] = ''; //默认不使用code, 该值用于其他系统导入时的初次认证
        $user['user_pwd'] = md5($user_data['user_pwd'].$user['code']);

        /*
        //载入会员整合，手机端没填：email，暂时不做会员整合;
        $integrate_code = trim(app_conf("INTEGRATE_CODE"));
        if($integrate_code!='')
        {
            $integrate_file = APP_ROOT_PATH."system/integrate/".$integrate_code."_integrate.php";
            if(file_exists($integrate_file))
            {
                require_once $integrate_file;
                $integrate_class = $integrate_code."_integrate";
                $integrate_obj = new $integrate_class;
            }
        }

        //同步整合
        if($integrate_obj)
        {
            $res = $integrate_obj->add_user($user_data['user_name'],$user_data['user_pwd'],$user_data['email']);
            $user['integrate_id'] = intval($res['data']);

            if(intval($res['status'])==0) //整合注册失败
            {
                return $res;
            }
        }

         $s_api_user_info = es_session::get("api_user_info");
        $user[$s_api_user_info['field']] = $s_api_user_info['id'];
        es_session::delete("api_user_info");
        */
        if($GLOBALS['db']->autoExecute(DB_PREFIX."user",$user,'INSERT'))
        {
            $user_id = $GLOBALS['db']->insert_id();

            if((int)app_conf("OPEN_IPS") > 0){
                $email = get_site_email($user_id);
                //$GLOBALS['db']->query("UPDATE ".DB_PREFIX."user SET email='$email' where id=".$user_id);
                if($user_data['mobile']){
                    $GLOBALS['db']->query("UPDATE ".DB_PREFIX."user SET email = '".$email."' ,email_encrypt = AES_ENCRYPT('".$email."','".AES_DECRYPT_KEY."'),mobile_encrypt = AES_ENCRYPT('".$user_data['mobile']."','".AES_DECRYPT_KEY."') where id=".$user_id);
                }else{
                    $GLOBALS['db']->query("UPDATE ".DB_PREFIX."user SET email = '".$email."' ,email_encrypt = AES_ENCRYPT('".$email."','".AES_DECRYPT_KEY."') where id=".$user_id);
                }

            }



            send_register_reward($user_id,"",$user['pid']);

        }


        return $user_id;
    }

    function check_user($user_data){
        //开始数据验证
        $res = array('status'=>1,'info'=>'','data'=>'','error_msg'=>''); //用于返回的数据

        if($user_data['user_pwd'] != $user_data['user_pwd_confirm'])
        {
            $res['status'] = 0;
            $res['error_msg'] = $GLOBALS['lang']['USER_PWD_CONFIRM_ERROR'];
            return  $res;
        }

        if(trim($user_data['user_pwd'])=='')
        {
            $res['status'] = 0;
            $res['error_msg'] = $GLOBALS['lang']['USER_PWD_ERROR'];
            return  $res;
        }

        if($res['status'] == 1 && trim($user_data['user_name'])=='')
        {
            $field_item['field_name'] = 'user_name';
            $field_item['error']	=	EMPTY_ERROR;
            $res['status'] = 0;
            $res['data'] = $field_item;
        }

        if($res['status'] == 1 && trim(!preg_match("/^(?!_|\s\')[A-Za-z0-9_\x80-\xff\']+$/",$user_data['user_name']) ||  preg_match('/^\d+$/i',$user_data['user_name']) || strLen($user_data['user_name']) > 15 || strLen($user_data['user_name']) < 3))
        {
            $field_item['field_name'] = 'user_name';
            $field_item['error']	=	FORMAT_ERROR;
            $res['status'] = 0;
            $res['data'] = $field_item;
        }

        if($res['status'] == 1 && $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user where user_name = '".trim($user_data['user_name'])."' and id <> ".intval($user_data['id']))>0)
        {
            $field_item['field_name'] = 'user_name';
            $field_item['error']	=	EXIST_ERROR;
            $res['status'] = 0;
            $res['data'] = $field_item;
        }

        if($res['status'] == 1 && trim($user_data['mobile'])=='')
        {
            $field_item['field_name'] = 'mobile';
            $field_item['error']	=	EMPTY_ERROR;
            $res['status'] = 0;
            $res['data'] = $field_item;
        }

        if($res['status'] == 1 && !check_mobile(trim($user_data['mobile'])))
        {
            $field_item['field_name'] = 'mobile';
            $field_item['error']	=	FORMAT_ERROR;
            $res['status'] = 0;
            $res['data'] = $field_item;
        }

        //if($res['status'] == 1 && $user_data['mobile']!=''&&$GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user where mobile = '".trim($user_data['mobile'])."' and id <> ".intval($user_data['id']))>0)
        if($res['status'] == 1 && $user_data['mobile']!=''&&$GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user where mobile_encrypt = AES_ENCRYPT('".trim($user_data['mobile'])."','".AES_DECRYPT_KEY."') and id <> ".intval($user_data['id']))>0)
        {
            $field_item['field_name'] = 'mobile';
            $field_item['error']	=	EXIST_ERROR;
            $res['status'] = 0;
            $res['data'] = $field_item;
        }

        if ($res['status'] == 0){
            $error = $res['data'];
            $error_msg = "";
            if(!$error['field_show_name'])
            {
                $error['field_show_name'] = $GLOBALS['lang']['USER_TITLE_'.strtoupper($error['field_name'])];
            }
            if($error['error']==EMPTY_ERROR)
            {
                $error_msg = sprintf($GLOBALS['lang']['EMPTY_ERROR_TIP'],$error['field_show_name']);
            }
            if($error['error']==FORMAT_ERROR)
            {
                $error_msg = sprintf($GLOBALS['lang']['FORMAT_ERROR_TIP'],$error['field_show_name']);
            }
            if($error['error']==EXIST_ERROR)
            {
                $error_msg = sprintf($GLOBALS['lang']['EXIST_ERROR_TIP'],$error['field_show_name']);
            }
            //showErr($error_msg);

            $res['error_msg'] = $error_msg;
        }

        return $res;
    }
}
?>